<!--
 * @Author: Xujianchen
 * @Date: 2024-06-24 11:54:21
 * @LastEditors: xujianchen
 * @LastEditTime: 2024-07-10 11:35:55
 * @Description: 富文本编辑器组件
-->
<template>
  <div :class="['editor-box', isDisabled ? 'editor-disabled' : '']">
    <Toolbar v-if="!hideToolBar" class="editor-toolbar" :editor="editorRef" :default-config="toolbarConfig"
      :mode="mode" />
    <Editor v-model="modelValue" class="editor-content" :style="{ height }" :mode="mode" :default-config="editorConfig"
      @on-created="handleCreated" />
  </div>
</template>

<script setup>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { loadCSS } from '@/utils/utils'

const modelValue = defineModel({ type: String, default: '' })
const props = defineProps({
  toolbarConfig: {
    type: Object,
    default: () => ({
      excludeKeys: [],
    }),
  },
  editorConfig: {
    type: Object,
    default: () => ({
      placeholder: '请输入内容...',
      MENU_CONF: {},
    }),
  },
  height: {
    type: String,
    default: '600px',
  },
  mode: {
    type: String,
    default: 'default',
  },
  hideToolBar: {
    type: Boolean,
    default: false,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
})

const editorRef = shallowRef(null)

const isDisabled = computed(() => props.disabled)

if (isDisabled.value) nextTick(() => editorRef.value.disable())

onMounted(() => loadCSS('https://cdn.bootcdn.net/ajax/libs/wangeditor5/5.1.23/css/style.min.css'))

onBeforeUnmount(() => {
  const instance = editorRef.value
  if (!instance) return
  instance.destroy()
})

function handleCreated(editor) {
  editorRef.value = editor
}

defineExpose({ editorRef })
</script>

<style>
/* FIXME: 编辑区域高度 < 300px 这可能会导致 modal hoverbar 定位异常 */
.w-e-scroll {
  height: auto;
}
</style>
<style lang="scss" scoped>
.editor-disabled {
  cursor: not-allowed !important;
}

.editor-box {
  /* FIXME: 防止富文本编辑器全屏时 tabs组件 在其层级之上 */
  z-index: 2;
  border: 1px solid var(--el-border-color);
  margin-top: $space-medium-s;

  .editor-toolbar {
    border-bottom: 1px solid var(--el-border-color);
  }

  .editor-content {
    overflow-y: hidden;
  }
}
</style>
